package com.open.capacity.study.service.impl;

import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.LearnIter;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.study.dao.LearnIterDao;
import com.open.capacity.study.service.LearnIterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class LearnIterServiceImpl implements LearnIterService {
    @Autowired
    private LearnIterDao learnIterDao;

    /**
     * 新增阶段内容
     * @param learnIter
     * @return
     * @throws ServiceException
     */
    @Override
    public Result insert(LearnIter learnIter) throws ServiceException {
        try {
            //判断数据是否重复存在
            LearnIter li = learnIterDao.findByIdAndCode(learnIter);
            if (li == null){
                learnIter.setCretim(new Date());
                int res = learnIterDao.insert(learnIter);
                log.info("新增阶段迭代进度:{}",learnIter);
                return res > 0 ? Result.succeed(learnIter,"新增成功"):Result.failed("新增失败");
            }
            else {
                return Result.failed("请勿重复添加数据");
            }
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    /**
     * 根据用户和阶段查找学习内容
     * @param params
     * @return
     * @throws ServiceException
     */
    @Override
    public PageResult<LearnIter> query(Map<String, Object> params) throws ServiceException {
        try {
            int count = learnIterDao.count(params);
            PageUtil.pageParamConver(params,false);
            List<LearnIter> list = Collections.emptyList();
            list = learnIterDao.findList(params);
            return PageResult.<LearnIter>builder().data(list).count((long) count).code(0).build();
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

}
